package com.developer.t24haber.util;

import java.util.List;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v4.app.ListFragment;
import android.util.Log;

import com.developer.t24haber.model.News;
import com.developer.t24haber.model.NewsParser;

public class NewsDownloader extends AsyncTask<String, Void, List<News>> {

	public static final String TAG = NewsDownloader.class.getName();

	private ProgressDialog progressDialog;
	private List<News> news;

	private final ListFragment listFragment;

	public NewsDownloader(ListFragment listFragment) {
		this.listFragment = listFragment;
	}

	@Override
	protected void onPreExecute() {
		this.progressDialog = new ProgressDialog(listFragment.getActivity());
		this.progressDialog.setTitle("Güncelleniyor");
		this.progressDialog.setMessage("Haberler indiriliyor...");
		this.progressDialog.setCancelable(false);
		this.progressDialog.setIndeterminate(true);
		this.progressDialog.show();
	}

	@Override
	protected List<News> doInBackground(String... params) {
		NewsParser newsParser = new NewsParser(params[0]);
		try {
			news = newsParser.getNews();
			for (News currentNews : news) {
				currentNews.setImage(Util.getInstance(listFragment.getActivity()).downloadImage(currentNews.getImageUrl()));
			}
		} catch (Exception e) {
			Log.e(TAG, e.getMessage(), e);
		}
		return news;
	}

	@Override
	protected void onPostExecute(List<News> result) {
		this.progressDialog.dismiss();
		NewsListAdapter listAdapter = new NewsListAdapter(result, listFragment);
		listFragment.setListAdapter(listAdapter);
	}

	public List<News> getNews() {
		return news;
	}

}
